import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { useAuth } from '../hooks/useAuth';
import {
  UserIcon,
  EnvelopeIcon,
  CalendarIcon,
  PencilIcon,
  CheckIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import api from '../services/api';
import LoadingSpinner from '../components/LoadingSpinner';
import toast from 'react-hot-toast';

const Profile = () => {
  const { user } = useAuth();
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState({
    first_name: user?.first_name || '',
    last_name: user?.last_name || '',
    email: user?.email || '',
  });
  const queryClient = useQueryClient();

  // 更新用户信息
  const updateProfileMutation = useMutation(
    (data) => api.put('/users/profile', data),
    {
      onSuccess: () => {
        queryClient.invalidateQueries('currentUser');
        setIsEditing(false);
        toast.success('个人信息更新成功');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '更新失败');
      },
    }
  );

  // 修改密码
  const changePasswordMutation = useMutation(
    (data) => api.post('/auth/change-password', data),
    {
      onSuccess: () => {
        toast.success('密码修改成功');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '密码修改失败');
      },
    }
  );

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSave = () => {
    updateProfileMutation.mutate(formData);
  };

  const handleCancel = () => {
    setFormData({
      first_name: user?.first_name || '',
      last_name: user?.last_name || '',
      email: user?.email || '',
    });
    setIsEditing(false);
  };

  const handlePasswordChange = (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const passwordData = {
      current_password: formData.get('current_password'),
      new_password: formData.get('new_password'),
    };
    changePasswordMutation.mutate(passwordData);
    e.target.reset();
  };

  const formatDate = (dateString) => {
    if (!dateString) return '未知';
    return new Date(dateString).toLocaleDateString();
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-2xl font-bold text-gray-900">个人资料</h1>
        <p className="mt-1 text-sm text-gray-500">
          管理您的个人信息和账户设置
        </p>
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
        {/* 个人信息 */}
        <div className="lg:col-span-2">
          <div className="card">
            <div className="card-header">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium text-gray-900">个人信息</h3>
                {!isEditing ? (
                  <button
                    onClick={() => setIsEditing(true)}
                    className="btn-outline"
                  >
                    <PencilIcon className="h-4 w-4 mr-2" />
                    编辑
                  </button>
                ) : (
                  <div className="flex space-x-2">
                    <button
                      onClick={handleSave}
                      disabled={updateProfileMutation.isLoading}
                      className="btn-success"
                    >
                      <CheckIcon className="h-4 w-4 mr-2" />
                      {updateProfileMutation.isLoading ? '保存中...' : '保存'}
                    </button>
                    <button
                      onClick={handleCancel}
                      className="btn-outline"
                    >
                      <XMarkIcon className="h-4 w-4 mr-2" />
                      取消
                    </button>
                  </div>
                )}
              </div>
            </div>
            <div className="card-body">
              <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
                <div>
                  <label className="block text-sm font-medium text-gray-700">用户名</label>
                  <input
                    type="text"
                    value={user?.username || ''}
                    disabled
                    className="mt-1 input bg-gray-50"
                  />
                  <p className="mt-1 text-sm text-gray-500">用户名不可修改</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">邮箱</label>
                  <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    className={`mt-1 input ${!isEditing ? 'bg-gray-50' : ''}`}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">名字</label>
                  <input
                    type="text"
                    name="first_name"
                    value={formData.first_name}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    className={`mt-1 input ${!isEditing ? 'bg-gray-50' : ''}`}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700">姓氏</label>
                  <input
                    type="text"
                    name="last_name"
                    value={formData.last_name}
                    onChange={handleInputChange}
                    disabled={!isEditing}
                    className={`mt-1 input ${!isEditing ? 'bg-gray-50' : ''}`}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 账户信息 */}
        <div className="space-y-6">
          {/* 头像 */}
          <div className="card">
            <div className="card-header">
              <h3 className="text-lg font-medium text-gray-900">头像</h3>
            </div>
            <div className="card-body text-center">
              <div className="mx-auto h-20 w-20 rounded-full bg-primary-500 flex items-center justify-center">
                <span className="text-2xl font-medium text-white">
                  {user?.username?.charAt(0).toUpperCase()}
                </span>
              </div>
              <p className="mt-2 text-sm text-gray-500">
                {user?.first_name && user?.last_name 
                  ? `${user.first_name} ${user.last_name}`
                  : user?.username
                }
              </p>
            </div>
          </div>

          {/* 账户统计 */}
          <div className="card">
            <div className="card-header">
              <h3 className="text-lg font-medium text-gray-900">账户统计</h3>
            </div>
            <div className="card-body">
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-500">注册时间</span>
                  <span className="text-sm font-medium text-gray-900">
                    {formatDate(user?.created_at)}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-500">最后登录</span>
                  <span className="text-sm font-medium text-gray-900">
                    {formatDate(user?.last_login)}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-500">账户状态</span>
                  <span className={`status-badge ${user?.is_active ? 'status-done' : 'status-cancelled'}`}>
                    {user?.is_active ? '活跃' : '已禁用'}
                  </span>
                </div>
                {user?.is_admin && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">权限</span>
                    <span className="status-badge bg-purple-100 text-purple-800">
                      管理员
                    </span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 修改密码 */}
      <div className="card">
        <div className="card-header">
          <h3 className="text-lg font-medium text-gray-900">修改密码</h3>
        </div>
        <div className="card-body">
          <form onSubmit={handlePasswordChange} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700">当前密码</label>
              <input
                type="password"
                name="current_password"
                required
                className="mt-1 input"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700">新密码</label>
              <input
                type="password"
                name="new_password"
                required
                minLength={8}
                className="mt-1 input"
              />
              <p className="mt-1 text-sm text-gray-500">
                密码必须至少8位，包含字母和数字
              </p>
            </div>
            <div>
              <button
                type="submit"
                disabled={changePasswordMutation.isLoading}
                className="btn-primary"
              >
                {changePasswordMutation.isLoading ? '修改中...' : '修改密码'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Profile;
